<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Demand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Requests\Logic\Demand\StoreResource;

/**
 * 项目用人需求数据模型
 *
 * Date: 25/04/2018
 * @author George
 * @package App\Http\Controllers
 */
class DemandController extends Controller
{
	/**
	 * Date: 25/04/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(Request $request)
    {
		$date = $request->get('date');
		$start = $request->get('start');
		$end = $request->get('end');
		$project_id = $request->get('project_id');
		$query = Demand::query()->with('genre')->where('project_id', $project_id);

		// 根据开始和结束时间查询
		$query->when($start && $end, function ($query) use ($start, $end) {
			/**
			 * @var Builder $query
			 */
			return $query->whereBetween('date', [$start, $end]);
		});

		// 查询指定日期的数据
		$query->when($date, function ($query, $date) {
			/**
			 * @var Builder $query
			 */
			return $query->where('date', $date);
		});

    	return success($query->get());
    }

	/**
	 * 创建用人需求
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws Exception
	 */
    public function store(StoreResource $request)
    {
    	$project_id = $request->project_id;
    	$days = $request->demands;
    	$demands = [];
    	DB::beginTransaction();
		try {
			foreach ($days as $day) {
				foreach ($day['genres'] as $genre) {
					$attributes = [
						'date' => $day['date'],
						'project_id' => $project_id,
						'genre_id' => $genre['id'],
						'staff' => $genre['staff'],
						'created_at' => date('Y-m-d H:i:s'),
						'updated_at' => date('Y-m-d H:i:s')
					];
					$demands[] = Demand::create($attributes);
				}
			}
			DB::commit();
			return stored($demands);
		} catch (Exception $exception) {
			DB::rollBack();
			return failed('创建记录失败，可能是数据重复');
		}
    }

	/**
	 * 获取指定的需求信息
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param Demand $demand
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function show(Demand $demand)
    {
    	return success($demand);
    }

	/**
	 * 更新用人需求数量
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param Request $request
	 * @param Demand $demand
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function update(Request $request, Demand $demand)
    {
    	$attributes = $this->validate($request, [
    		'staff' => 'required'
		]);

    	$demand->update($attributes);
    	return updated($demand);
    }

	/**
	 * 删除项目用人需求
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param Demand $demand
	 * @return \Illuminate\Http\JsonResponse
	 * @throws Exception
	 */
    public function destroy(Demand $demand)
    {
    	$demand->delete();
    	return deleted();
    }
}
